﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;

namespace ExaminationSys.View.SystemManage
{
    public partial class DBSubjectQuestionEdit : System.Web.UI.UserControl
    {
        private static readonly DBSubjectQuestionService Proxy = ObjectFactory<DBSubjectQuestionService>.Create();
        private static readonly DBQuestionService ProxyQuestion = ObjectFactory<DBQuestionService>.Create();
        private static readonly DBAnswerService ProxyDBAnswer = ObjectFactory<DBAnswerService>.Create();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                Bind();
            }
        }
        private void Bind()
        {
            // TO DO
        }

        public Store GridStore { get; set; }
        public string ID { get; set; }


        public void SetData(string id, string subjectid, string title, string stage)
        {
            SubjectTitle.Value = title;
            DBSubjectQuestionEditPanel.Title = "  大题_标题： " + title;
            lblTitle2.Value = subjectid;
            X.Js.Call("subjectid", subjectid);
            txtStage.Text = stage;

            #region 初始化
            if (string.IsNullOrEmpty(id))
            {
                KeyWord.Text = "";
                Knowledge.Text = "";
                QuestionType.Text = "请选择类型";
                SubjectType.Text = "";
                Challenge.Text = "";
                Point.Text = "0";
                AttachFile.Text = "";
                Content.Text = "";
                txtA.Text = "";
                txtB.Text = "";
                txtC.Text = "";
                txtD.Text = "";
                txtE.Text = "";
                chkA.Checked = false;
                chkB.Checked = false;
                chkC.Checked = false;
                chkD.Checked = false;
                chkE.Checked = false;
                txtA.Tag = "";
                txtB.Tag = "";
                txtC.Tag = "";
                txtD.Tag = "";
                txtE.Tag = "";
                txtSerialNo.Value = "";
                txtIDA.Text = "";
                txtIDB.Text = "";
                txtIDC.Text = "";
                txtIDD.Text = "";
                txtIDE.Text = "";
                txtAttachFile.Value = "";
                X.Js.Call("setDBSubjectQuestionID", "");
                this.DBSubjectQuestionEditWindow.Title = "题库管理(大题--小题)新增";

                QuestionType.Select(0);
                Challenge.Select(2);
                Point.Number = 1;
                SubjectType.Select(0);
            }
            #endregion
            else
            {
                this.DBSubjectQuestionEditWindow.Title = "题库管理(大题--小题)修改";
                DBSubjectQuestion dBSubjectQuestion = Proxy.Get(new Guid(subjectid));
                var realId = new Guid(id);
                var dbquestion = ProxyQuestion.Get(realId);

                KeyWord.Text = dbquestion.KeyWord;
                Knowledge.Text = dbquestion.Knowledge;
                QuestionType.Text = dbquestion.QuestionType;
                SubjectType.Text = dbquestion.SubjectType;
                Challenge.Text = dbquestion.Challenge;
                Point.Text = dbquestion.Point.ToString();
                AttachFile.Text = dbquestion.AttachFile;
                AttachFile.Text = dbquestion.AttachFile;
                Content.Text = dbquestion.Content;
                txtAttachFile.Value = dbquestion.AttachFile;
                txtSerialNo.Value = dbquestion.SerialNo;
                txtOrderIndex.Text = dBSubjectQuestion == null ? dbquestion.OrderIndex.ToString() : dBSubjectQuestion.OrderIndex.ToString();
                X.Js.Call("attachFile", dbquestion.AttachFile);
                X.Js.Call("serialNo", dbquestion.SerialNo);

                List<DBAnswer> list = ProxyDBAnswer.GetAll(dbquestion.ID);
                Window w = this.DBSubjectQuestionEditWindow;
                string prefix = string.Empty;
                foreach (DBAnswer dbanswer in list)
                {
                    prefix = dbanswer.Prefix.Trim();
                    TextField txt = w.FindControl("txt" + prefix) as TextField;
                    Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                    TextField txtid = w.FindControl("txtID" + prefix) as TextField;

                    txt.Text = dbanswer.Content;
                    txtid.Text = dbanswer.ID.ToString();
                    chk.Checked = dbanswer.IsRight;

                    prefix = string.Empty;
                }
                LockHidden.Value = dbquestion.Lock.ToString();
                chkLock.Checked = dbquestion.Lock;
                X.Js.Call("lock", dbquestion.Lock);

                ID = id;
                X.Js.Call("setDBSubjectQuestionID", id);
            }
        }

        public void Show()
        {
            this.DBSubjectQuestionEditWindow.Show();
        }

        protected void SaveDBSubjectQuestion(object sender, DirectEventArgs e)
        {
            List<string> listPrefix = new List<string>();
            listPrefix.Add("A");
            listPrefix.Add("B");
            listPrefix.Add("C");
            listPrefix.Add("D");
            listPrefix.Add("E");

            var keyword = KeyWord.Text.Trim();
            var knowledge = Knowledge.Text.Trim();
            var questiontype = QuestionType.Text.Trim();// 请选择类型
            var subjecttype = SubjectType.Text.Trim(); // 题型
            var challenge = Challenge.Text.Trim(); // 难度
            var point = Point.Text.Trim();
            var content = Content.Text.Trim();
            var attachfile = txtAttachFile.Value;
            var orderindex = txtOrderIndex.Text;

            bool questionexists = ProxyQuestion.CheckContent(content, "小题");
            if (questionexists && string.IsNullOrEmpty(DBSubjectQuestionIDHidden.Value))
            {
                MessageBoxHelper.ShowWarning("该题已经存在");
                return;
            }
            // 答案
            bool flag = AnswerContentCheck(listPrefix);
            if (!flag)
                return;

            if (AttachFile.HasFile && subjecttype.Equals("视听"))
            {
                #region 附件上传
                attachfile = this.AttachFile.PostedFile.FileName.ToString();
                string strFileName = Path.GetExtension(this.AttachFile.PostedFile.FileName).ToUpper();
                //获取文件后缀              
                if (!(strFileName == ".MP3" || strFileName == ".MP4" || strFileName == ".AVI"))
                {
                    MessageBoxHelper.ShowWarning("文件格式不正确！\r\n只能上传MP3、MP4、AVI 文件");
                    return;
                }

                int FileSize = Int32.Parse(this.AttachFile.PostedFile.ContentLength.ToString());
                if (FileSize > 30 * 1024 * 1024)
                {
                    MessageBoxHelper.ShowWarning("上传文件过大");
                    return;
                }

                var fileNameTmp = Path.GetFileName(this.AttachFile.PostedFile.FileName);
                string fileName = string.Format("{0}_{1}_{2}", Guid.NewGuid().ToString(), DateTime.Now.ToString("yyyyMMddHHmm"), fileNameTmp);
                var filePath = string.Format("{0}/DBQuestion", UIHelpers.BasePath);
                string fileFullName = Path.Combine(Server.MapPath(filePath), fileName);

                try
                {
                    this.AttachFile.PostedFile.SaveAs(fileFullName);
                    attachfile = fileName;
                    txtAttachFile.Value = fileName;
                }
                catch (Exception ex)
                {
                    MessageBoxHelper.ShowError("附件上传出错", ex.Message);
                    return;
                }
                #endregion
            }
            else if (!subjecttype.Equals("视听"))
                attachfile = string.Empty;

            // 题目
            #region 条件

            //if (string.IsNullOrWhiteSpace(keyword))
            //{
            //    MessageBoxHelper.ShowWarning("关键字不能为空");
            //    return;
            //}
            //if (string.IsNullOrWhiteSpace(knowledge))
            //{
            //    MessageBoxHelper.ShowWarning("知识点不能为空");
            //    return;
            //}
            if (string.IsNullOrEmpty(questiontype))
            {
                MessageBoxHelper.ShowWarning("类型不能为空");
                return;
            }
            if (string.IsNullOrEmpty(subjecttype))
            {
                MessageBoxHelper.ShowWarning("题型不能为空");
                return;
            }
            if (string.IsNullOrEmpty(challenge))
            {
                MessageBoxHelper.ShowWarning("难度不能为空");
                return;
            }
            if (string.IsNullOrEmpty(point))
            {
                MessageBoxHelper.ShowWarning("分值不能为空");
                return;
            }
            if (string.IsNullOrEmpty(content))
            {
                MessageBoxHelper.ShowWarning("内容不能为空");
                return;
            }
            if (string.IsNullOrEmpty(orderindex))
            {
                MessageBoxHelper.ShowWarning("排序不能为空");
                return;
            }
            if (subjecttype.Equals("视听") && string.IsNullOrEmpty(attachfile))
            {
                MessageBoxHelper.ShowWarning("视听题，视听附件不能为空");
                return;
            }

            #endregion



            var id = DBSubjectQuestionIDHidden.Value;
            var actionflag = string.IsNullOrWhiteSpace(id);
            Guid realId = string.IsNullOrEmpty(id) ? Guid.NewGuid() : new Guid(id);

            ExaminationSys.DataAccess.Entity.DBQuestion entity = new DataAccess.Entity.DBQuestion();
            string headstr = System.DateTime.Now.ToString("yyyyMMdd");
            entity.ID = realId;
            entity.SerialNo = string.IsNullOrEmpty(txtSerialNo.Value) ? ProxyQuestion.GetSerialNo(headstr) : txtSerialNo.Value;
            entity.KeyWord = keyword;
            entity.Knowledge = knowledge;
            entity.QuestionType = questiontype;
            entity.DBQuestionType = "小题";
            entity.SubjectType = subjecttype;
            entity.Challenge = challenge;
            entity.Point = Decimal.Parse(point);
            entity.AttachFile = attachfile;
            entity.Content = content;
            entity.OrderIndex = int.Parse(orderindex);

            entity.Title = SubjectTitle.Value;
            entity.Stage = txtStage.Text;
            entity.Status = 1;
            entity.AddTime = DateTime.Now;
            entity.Lock = chkLock.Checked;

            var op = FormsAuthenticationHelper.GetCurrentUserID();
            if (string.IsNullOrEmpty(op))
            {
                FormsAuthenticationHelper.SignOut();
                Response.Redirect("~/Account/Login.aspx");
            }
            entity.Operator = op;

            entity.OperatorTime = DateTime.Now;


            var sucess = false;

            //if (actionflag)
            //{
            //    var retCode = ProxyQuestion.Insert(entity);
            //    sucess = retCode != null;
            //    sucess = AnswerAddOrUpdate(sucess, retCode, listPrefix, true);
            //}
            //else
            //{
            //    sucess = ProxyQuestion.Update(entity);
            //    sucess = AnswerAddOrUpdate(sucess, realId, listPrefix, false);
            //}
            DBSubjectQuestion dBSubjectQuestion = SubjectQuestionForAdd(entity);
            List<DBAnswer> listdBAnswer = new List<DBAnswer>();
            listdBAnswer = AnswerAddOrUpdate3(entity, listPrefix);

            sucess = ProxyQuestion.AnswerAddOrUpdate(entity, listdBAnswer, actionflag, dBSubjectQuestion);

            if (sucess)
            {
                Proxy.Update(realId);
                GridStore.Reload();
                DBSubjectQuestionEditWindow.Hide();
                //MessageBoxHelper.ShowInfo("保存成功");
            }
            else
            {
                MessageBoxHelper.ShowInfo("保存失败");
                return;
            }
        }

        /// <summary>
        /// 答案选项检查
        /// </summary>
        /// <returns></returns>
        private bool AnswerContentCheck(List<string> listPrfix)
        {
            var questiontype = QuestionType.Text.Trim();
            Window w = this.DBSubjectQuestionEditWindow;
            int all = 0, chkall = 0;
            foreach (string prefix in listPrfix)
            {
                TextField txt = w.FindControl("txt" + prefix) as TextField;
                Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                if (string.IsNullOrEmpty(txt.Text.Trim()) && chk.Checked)
                {
                    MessageBoxHelper.ShowWarning("答案内容为空不能是正确答案");
                    return false;
                }
                if (!string.IsNullOrEmpty(txt.Text.Trim()))
                    all++;
                if (chk.Checked)
                    chkall++;
            }
            if (questiontype.Equals("单选"))
            {
                if (all < 2)
                {
                    MessageBoxHelper.ShowWarning("单选题：答案选项必须至少为两个");
                    return false;
                }
                else if (chkall != 1)
                {
                    MessageBoxHelper.ShowWarning("单选题：正确答案有且只有一个");
                    return false;
                }
            }
            else if (questiontype.Equals("多选"))
            {
                if (all < 3)
                {
                    MessageBoxHelper.ShowWarning("多选题：答案选项必须至少为三个");
                    return false;
                }
                else if (chkall < 2)
                {
                    MessageBoxHelper.ShowWarning("多选题：正确答案必须大于一个");
                    return false;
                }
            }
            return true;
        }

        private bool SubjectQuestionAdd(Guid qid)
        {
            Guid subjectid = new Guid(lblTitle2.Value);
            bool flag = Proxy.ChecKSubjectQuestion(subjectid, qid);
            if (!flag)
            {
                DBSubjectQuestion dbsubjectquestion = new DBSubjectQuestion();

                dbsubjectquestion.DBQuestionID = qid;
                dbsubjectquestion.DBSubjectID = subjectid;
                dbsubjectquestion.OrderIndex = Proxy.GetMaxOrderIndex(subjectid) + 1;
                dbsubjectquestion.ID = Guid.NewGuid();
                dbsubjectquestion.Lock = false;

                var op = FormsAuthenticationHelper.GetCurrentUserID();
                if (string.IsNullOrEmpty(op))
                {
                    FormsAuthenticationHelper.SignOut();
                    Response.Redirect("~/Account/Login.aspx");
                }
                dbsubjectquestion.Operator = op;

                dbsubjectquestion.OperatorTime = DateTime.Now;
                dbsubjectquestion.Status = 1;

                var retCode = Proxy.Insert(dbsubjectquestion);
                return retCode != null;
            }
            return false;
        }

        /// <summary>
        /// 答案项更新
        /// </summary>
        private bool AnswerAddOrUpdate(bool sucess, Guid realId, List<string> listPrefix, bool addFlag)
        {
            if (sucess)
            {
                string str = lblTitle2.Value;
                if (addFlag)
                    sucess = SubjectQuestionAdd(realId);

                if (sucess)
                {
                    sucess = AnswerAddOrUpdate2(listPrefix, realId, addFlag);

                    if (!sucess)
                    {
                        List<string> listsq = new List<string>();
                        listsq.Add(realId.ToString());
                        ProxyQuestion.Delete(listsq);

                        Proxy.Delete(new Guid(lblTitle2.Value), realId);
                    }
                }
                else
                {
                    List<string> list = new List<string>();
                    list.Add(realId.ToString());
                    ProxyQuestion.Delete(list);
                }
            }
            return sucess;
        }

        private bool AnswerAddOrUpdate2(List<string> listPrefix, Guid realId, bool addFlag)
        {
            if (listPrefix != null && listPrefix.Count > 0)
            {
                List<string> listDelete = new List<string>();
                try
                {
                    foreach (string prefix in listPrefix)
                    {
                        DBAnswer dbanswer = new DBAnswer();
                        dbanswer.Lock = false;
                        dbanswer.Status = 1;
                        dbanswer.OperatorTime = DateTime.Now;

                        var op = FormsAuthenticationHelper.GetCurrentUserID();
                        if (string.IsNullOrEmpty(op))
                        {
                            FormsAuthenticationHelper.SignOut();
                            Response.Redirect("~/Account/Login.aspx");
                        }
                        dbanswer.Operator = op;

                        dbanswer.DBQuestionID = realId;

                        Window w = this.DBSubjectQuestionEditWindow;

                        TextField txt = w.FindControl("txt" + prefix) as TextField;
                        Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                        TextField txtid = w.FindControl("txtID" + prefix) as TextField;

                        if ((addFlag || string.IsNullOrEmpty(txtid.Text)) && !string.IsNullOrEmpty(txt.Text.Trim()))
                        {
                            dbanswer.ID = Guid.NewGuid();
                            dbanswer.Prefix = prefix;
                            dbanswer.Content = txt.Text.Trim();
                            dbanswer.IsRight = chk.Checked;
                            var retCode = ProxyDBAnswer.Insert(dbanswer);
                            if (retCode != null)
                                listDelete.Add(dbanswer.ID.ToString());
                        }
                        else if (!string.IsNullOrEmpty(txtid.Text))
                        {
                            dbanswer.ID = new Guid(txtid.Text);
                            if (string.IsNullOrEmpty(txt.Text.Trim()))
                            {
                                List<string> list = new List<string>();
                                list.Add(dbanswer.ID.ToString());
                                ProxyDBAnswer.Delete(list);
                            }
                            else
                            {
                                dbanswer.Prefix = prefix;
                                dbanswer.Content = txt.Text.Trim();
                                dbanswer.IsRight = chk.Checked;
                                ProxyDBAnswer.Update(dbanswer);
                            }
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    ProxyDBAnswer.Delete(listDelete);
                }
            }
            return false;
        }

        private List<DBAnswer> AnswerAddOrUpdate3(DBQuestion dBquestion, List<string> listPrefix)
        {
            List<DBAnswer> listdBAnswer = new List<DBAnswer>();
            try
            {
                Window w = this.DBSubjectQuestionEditWindow;

                foreach (string prefix in listPrefix)
                {
                    TextField txt = w.FindControl("txt" + prefix) as TextField;
                    Checkbox chk = w.FindControl("chk" + prefix) as Checkbox;
                    TextField txtid = w.FindControl("txtID" + prefix) as TextField;

                    if (!string.IsNullOrEmpty(txt.Text.Trim()))
                    {
                        DBAnswer dbanswer = new DBAnswer();
                        dbanswer.Lock = false;
                        dbanswer.Status = 1;
                        dbanswer.OperatorTime = DateTime.Now;
                        dbanswer.Operator = dBquestion.Operator;
                        dbanswer.DBQuestionID = dBquestion.ID;
                        dbanswer.ID = Guid.NewGuid();
                        dbanswer.Prefix = prefix;
                        dbanswer.Content = txt.Text.Trim();
                        dbanswer.IsRight = chk.Checked;
                        listdBAnswer.Add(dbanswer);
                    }
                }
            }
            catch (Exception ex)
            {
                listdBAnswer = new List<DBAnswer>();
            }

            return listdBAnswer;
        }

        private DBSubjectQuestion SubjectQuestionForAdd(DBQuestion dBquestion)
        {
            Guid subjectid = new Guid(lblTitle2.Value);
            DBSubjectQuestion dbsubjectquestion = new DBSubjectQuestion();
            bool flag = Proxy.ChecKSubjectQuestion(subjectid, dBquestion.ID);
            dbsubjectquestion.DBQuestionID = dBquestion.ID;
            dbsubjectquestion.DBSubjectID = subjectid;
            dbsubjectquestion.ID = Guid.NewGuid();
            dbsubjectquestion.Lock = false;
            dbsubjectquestion.OperatorTime = DateTime.Now;
            dbsubjectquestion.Status = 1;
            dbsubjectquestion.OrderIndex = dBquestion.OrderIndex;

            return dbsubjectquestion;
        }
    }
}